<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
    <meta content="featon inc." name="author">
    <link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/vendor/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="/static/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="/static/vendor/skin/ftskin.css" rel="stylesheet">
    <link href="/static/vendor/webuploader/webuploader.css" rel="stylesheet" type="text/css">
    <link href="/static/vendor/datetimepicker/jquery.datetimepicker.css" rel="stylesheet">
    <title>添加(更新)产品信息</title>
    <style>

    </style>
</head>

<body style="margin-bottom: 60px;">

<div class="ft-subpage-wrapper container-fluid">
    <form action="#" id="form1" method="post" name="form1">
        <div class="row">
            <div class="col-lg-12" id="form_table">
                <fieldset>
                    <legend id="titleText">-添加(更新)产品信息-</legend>
                    <table cellpadding="0" cellspacing="0" class="form-table form-table-border" id="">
                        <tr>
                            <th><span class="f_red">*</span>产品名称</th>
                            <td colspan="3">
                                <input class="form-control" id="proName" name="proName" placeholder="" type="text"
                                       value="">
                                <span class="cError"></span>
                            </td>
                        </tr>
                        <tr>
                            <th><span class="f_red">*</span>产品分类</th>
                            <td colspan="3">
                                <select class="form-control" id="proType" name="proType">
                                    <option disabled id="proType_val" selected>--请选择--</option>
                                </select>
                                <span class="cError"></span>
                            </td>
                        </tr>
                        <tr>
                            <th><span class="f_red">*</span>品牌</th>
                            <td colspan="3">
                                <input class="form-control" id="brand" name="brand" placeholder="" type="text"
                                       value="">
                                <span class="cError"></span>
                            </td>
                        </tr>
                        <tr>
                            <th><span class="f_red">*</span>成分</th>
                            <td colspan="3">
                                <select class="form-control" id="component" name="component">
                                    <option disabled selected id="component_val">--请选择--</option>
                                </select>
                                <span class="cError"></span>
                            </td>
                        </tr>

                        <tr>
                            <th><span class="f_red">*</span>价格(¥)</th>
                            <td colspan="3">
                                <input class="form-control" id="price" name="price" placeholder="" type="number"
                                       value="">
                                <span class="cError"></span>
                            </td>
                        </tr>
                        <tr>
                            <th><span class="f_red">*</span>检测报告</th>
                            <td colspan="3">
                                <label data-container="body" data-content="" data-toggle="popover" for="report"
                                       id="input_label"
                                       style="border: 1px solid brown;border-radius: 10px;color: blue;background-color: burlywood;">
                                    <span id="report_label">选择上传报告</span>

                                    <input class="form-control" id="report" name="report" placeholder=""
                                           style="display: none" type="file"
                                           value="">
                                </label>
                                <span class="msg" style="color: red;display: none;line-height: 10px">
                                                !上传会覆盖现有的报告!
                                            </span>
                                <span class="cError"></span>
                            </td>
                        </tr>
                        <tr>
                            <th>产品照片</th>
                            <td colspan="3">
                                <div class="file" style="line-height: 0">
                                    <label id="uploadFile">
                                        <input id="photo" multiple="multiple" name="photo" style="display: none"
                                               type="file">
                                        <div style="text-align: center;height: 200px;width: 130px;border: 1px solid #a78888;border-radius: 3px">
                                            <br>
                                            <i class="glyphicon glyphicon-plus"
                                               style="font-size: 58px;color: #b9b8b6;"></i>
                                            <h3 style="color: #b9b8b6;">点击上传</h3>
                                            <span class="msg" style="color: red;display: none;line-height: 10px">
                                                <p>!上传会覆盖!</p>
                                                 <p>!现有的!</p>
                                                 <p>!所有照片!</p>
                                            </span>
                                        </div>
                                    </label>
                                </div>
                            </td>
                        </tr>
                    </table>
                </fieldset>
                <div class="bottom-tools-box">
                    <button class="btn btn-info" id="save_but" onclick="addAndUpdateObject()" type="button"><span
                            aria-hidden="true" class="glyphicon glyphicon-floppy-disk"></span> 保存
                    </button>
                    <button class="btn btn-warning" onclick="top.tab_colseOnclick();" type="button"><span
                            aria-hidden="true" class="glyphicon glyphicon-remove-circle"></span> 取消
                    </button>
                </div>

            </div>
        </div>
    </form>
</div>
<input th:id="id" th:value="${cpId}" type="hidden"/>

<script src="/static/vendor/jquery/jquery-3.3.1.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/static/vendor/validate/jquery.validate.min.js" type="text/javascript"></script>
<script src="/static/vendor/webuploader/webuploader.js" type="text/javascript"></script>
<script src="/static/vendor/skin/js/ft-ui.js"></script>
<script src="/static/vendor/skin/js/jquery.c.js"></script>
<script src="/static/vendor/skin/js/java.js"></script>
<script src="/static/vendor/skin/js/upload-util.js"></script>
<script src="/static/vendor/sortable/sortable.js"></script>
<script src="/static/vendor/datetimepicker/jquery.datetimepicker.js"></script>
<script>
    $("form input,form select").blur(function () {
        let siblings = $(this).siblings(".cError");
        $(siblings).empty();
        if ($(this).val().trim() === "" || $(this).val() === null) {
            $(siblings).append(`
            <span style="font-size: 12px;font-weight: bold;color: red">不能为空</span>
            `)
            $(this).focus();
        }
    })

    function iniInfoForm() {
        let validator = $("#form1").validate({
            debug: true,
            rules: {
                // user_realname: {
                //     required: true
                // },
                // dq_yw_name: {
                //     required: true
                // }
            },
            messages: {
                // user_realname: {
                //     required: "执法人员不能为空！"
                // },
                // dq_yw_name: {
                //     required: "所属地区不能为空"
                // }
            },
            errorPlacement: function (error, element) {
                error.appendTo(element.parents('td').find(".cError"));
            },
            submitHandler: function (form) {
            }
        });
    }

    let id = $("#id").val();
    $(function () {
        $("#proName").focus()
        if (id !== null && id !== '') {
            $.get("/pm/getObjByArgs?cpId=" + id, function (result) {
                $("#proName").val(result[0].proName);
                $("#proType_val").text(result[0].proType);
                $("#brand").val(result[0].brand);
                $("#component_val").text(result[0].component);
                $("#price").val(result[0].price);
                $("#remark").val(result[0].remark);
                $(".msg").show()
            })
        }
    })
    let is_submit = false;
    let url = "";
    if (id !== null && id !== '') {
        url = '/pm/updateProductInfo';
    } else {
        url = '/pm/addProductInfo';
    }
    let formData = new FormData();

    function addAndUpdateObject() {
        /* let files = document.getElementById('photo').files;*/
        let files = fileList;
        let report = document.getElementById('report').files[0];
        if (report === undefined && id === null) {
            alert("请选择检测报告")
            return false;
        }
        let length = files.length;
        formData.append("report", report)
        if (length === 0 && id !== null && id !== '') {
            let bean = {
                cpId: id,
                proName: $("#proName").val(),
                proType: $("#proType").val(),
                brand: $("#brand").val(),
                component: $("#component").val(),
                price: $("#price").val(),
                remark: $("#remark").val(),
            }
            let submit = true;
            if (id === null || id === '') {
                for (let beanKey in bean) {
                    let beanElement = bean[beanKey];
                    if ((beanElement === null || beanElement === "") && beanKey !== "id" && beanKey !== "remark") {
                        submit = false;
                        $("#" + beanKey).siblings(".cError").append(`<span style="font-size: 12px;font-weight: bold;color: red">不能为空</span>`);
                        return;
                    }
                }
            }
            if (submit) {
                if (top.ajax.synclBody(url, bean)) {
                    modelWindow.alert(top.CMSLang.Add_success);
                }
                top.getCurrentFrameObj().loadListble();
                top.tab_colseOnclick();
            }
        } else {
            for (let i = 0; i < length; i++) {
                formData.append("pics", files[i]);
            }
            formData.set("noSubmit", String(noSubmit))
            let imgUrl = 'nullUrl';
            $.ajax({
                url: "/cs/uploadPic",
                type: "post",
                data: formData,
                async: false,
                cache: false,
                dataType: 'json',
                contentType: false,//不设置内容类型
                processData: false, //不处理数据
                success: function (result) {
                    if (result !== null) {
                        imgUrl = result.photo
                        let bean = {
                            cpId: id,
                            proName: $("#proName").val(),
                            proType: $("#proType").val(),
                            brand: $("#brand").val(),
                            component: $("#component").val(),
                            price: $("#price").val(),
                            remark: $("#remark").val(),
                            photo: imgUrl,
                            report: result.report
                        }
                        let submit = true;
                        if (id === null || id === ''){
                            for (let beanKey in bean) {
                                let beanElement = bean[beanKey];
                                if ((beanElement === null || beanElement === "") && beanKey !== "id" && beanKey !== "remark") {
                                    submit = false;
                                    $("#" + beanKey).siblings(".cError").empty().append(`<span style="font-size: 12px;font-weight: bold;color: red">不能为空</span>`);
                                    return;
                                }
                            }
                        }
                        if (submit) {
                            if (top.ajax.synclBody(url, bean)) {
                                modelWindow.alert(top.CMSLang.Add_success);
                                top.getCurrentFrameObj().loadListble();
                                top.tab_colseOnclick();
                            } else {
                                modelWindow.alert(top.CMSLang.Add_fail);
                            }

                        }
                    } else {
                        alert("照片上传异常")
                    }
                },
                error: function () {
                    alert("提交失败")
                },

            });
        }
    }

    $("#proType").click(function () {
        let $that = $(this);
        let url = '/dictCategory/getDictList/pro_type';
        let children = $($that).children();
        $("#proType_val").hide();
        if (children.length <= 1) {
            $("#beeId_val").hide();
            $.get(url, function (result) {
                result.forEach((item) => {
                    $($that).append(`
                    <option value="` + item.dict_code + `">` + item.dict_name + `</option>
                `)
                })
            })
        }
    })
    $("#component").click(function () {
        let $that = $(this);
        let url = '/dictCategory/getDictList/component';
        let children = $($that).children();
        if (children.length <= 1) {
            $("#component_val").hide();
            $.get(url, function (result) {
                result.forEach((item) => {
                    $($that).append(`
                    <option value="` + item.dict_code + `">` + item.dict_name + `</option>
                `)
                })
            })
        }
    })

    $("#report").on('change', function () {
        let file = this.files[0];
        let name = file.name;
        let indexOf = name.lastIndexOf('.');
        let fileSuffix = name.slice(indexOf);
        let suffix = ['.doc', '.docx', '.pdf'];
        if (suffix.includes(fileSuffix)) {
            $("#report_label").css('color', '#615e57').text('已选择:' + name);
        } else {
            $("#input_label").attr('data-content', '请确认文件为 word或者pdf')
            $("#report_label").css('color', 'red').text('!文件格式错误!');
            $('#input_label').popover('show');
            $(this).val('');
        }
    })
    let index = '';
    let noSubmit = [];
    let fileList = [];
    $("#photo").on('change', function () {
        let files = this.files;
        for (let file of files) {
            fileList.push(file)
            if (window.FileReader) {
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onloadend = function (e) {
                    if (index !== '') {
                        noSubmit.push($(index).attr("img_name"))
                        console.log(noSubmit)
                        $(index).children('.image').attr('src', e.target.result);
                        $(index).attr("img_name", file.name);
                    } else {
                        $("#uploadFile").before(`
            <div class="img_box" img_name="` + file.name + `" style="position: relative;display: inline-block;">
                                        <img alt="" class="image" src="` + e.target.result + `"  style="width: 130px;height: 200px">
                                        <div class="img_btn" style="position: absolute;top:100px;left:40px; display: none">
                                            <label for="photo"
                                                   style="display: inline;;width: 60px;text-align: center;background-color: #28219e;color: #d8b0b0;border: 1px double;border-radius: 6px;">更&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;换</label>
                                        </div>
                                        <div class="img_btn_2"   style="position: absolute;top:140px;left:40px; display: none">
                                            <label style="display: inline;;width: 60px;text-align: center;background-color: #28219e;color: #d8b0b0;border: 1px double;border-radius: 6px;">删&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;除</label>
                                        </div>
                                    </div>
            `)
                    }
                };
            }
        }
    })
    $(".file").on("mouseover", ".img_box", function () {
        $(this).children(".img_btn,.img_btn_2").show()
        index = $(this);
    }).on("mouseout", ".img_box", function () {
        $(this).children(".img_btn,.img_btn_2").hide()
        index = '';
    }).on("click", ".img_btn_2", function () {
        noSubmit.push($(index).attr("img_name"))
        console.log(noSubmit)
        $(index).hide();
    });

</script>
</body>

</html>
